<script setup lang="ts">
import {defineEmits, ref} from 'vue'

const todayEnd = () => {
	const now = new Date();
	now.setHours(23);
	now.setMinutes(59);
	now.setSeconds(59);
	return now;
}

const nDayAgoStart = (n: number) => {
	const now = new Date()
	now.setTime(now.getTime() - 3600 * 1000 * 24 * n);
	now.setHours(0);
	now.setMinutes(0);
	now.setSeconds(0);
	return now;
}

const shortcuts = [
	{
		text: '近一周',
		value: () => {
			const end = todayEnd();
			const start = nDayAgoStart(7)
			return [start, end]
		},
	},
	{
		text: '近一月',
		value: () => {
			const end = todayEnd();
			const start = nDayAgoStart(30)
			return [start, end]
		},
	},
	{
		text: '近三月',
		value: () => {
			const end = todayEnd();
			const start = nDayAgoStart(90)
			return [start, end]
		},
	},
]

const initTimeRange = shortcuts[1].value.apply(() => {
})

const emit = defineEmits(['on-select'])

function onSelect(timeRange: [Date, Date] | null) {
	emit('on-select', timeRange)
}

const selectedTimeRange = ref<[Date, Date] | null>([initTimeRange[0], initTimeRange[1]])

function reset() {
	selectedTimeRange.value = null
}

defineExpose({reset})

onMounted(() => {
	onSelect(selectedTimeRange.value)
})
</script>

<template>
	<el-form-item label="创建时间">
		<el-date-picker
				v-model="selectedTimeRange"
				type="datetimerange"
				:shortcuts="shortcuts"
				range-separator="到"
				start-placeholder="开始时间"
				end-placeholder="结束时间"
				@change="onSelect"
		/>
	</el-form-item>
</template>
